	<?php
	ob_end_clean();
	ob_start();
?>
<html xmlns="http://www.w3.org/1999/xhtml" lang="ja" xml:lang="ja">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<meta http-equiv="Content-Script-Type" content="text/javascript" />
		<meta http-equiv="Content-Style-Type" content="text/css" />

	</head>
<body>
<?php
	require_once( '../system/smarty.inc' );
	require_once( '../system/mdao/Class_M_COST_DM_COUNT.php' );
	require_once( '../system/mdao/Class_M_COST_DM.php' );
	require_once( '../system/mdao/Class_M_OTHER.php' );
	require_once( '../system/Class_FILE_CSV.php' );
	require_once( '../system/Class_ERROR.php' );
	require_once( '../system/login.inc.php' );
	require_once( '../system/aoki_m.php' );
	require_once( '../system/Class_PWD.php' );
	
	Class_PWD::valid_auth(AOKI_AUTH_COST_DM,$login['staff_auth']);
	$docsv_import = FALSE;
	$csvf = Class_FILE_CSV::get_upload_file();
	$martrix_cd   =  $_POST['week_cd'];
	if ($csvf) {
			// ロケール情報の変更
		$locale = setlocale(LC_ALL, 0);
		setlocale(LC_ALL,'ja_JP.UTF-8');
		$rethead = true;
		$rowall = Class_FILE_CSV::fget_rows($csvf, true, $rethead);
			
		if  (!empty($rowall)) {
			$col_heads = array(
				'shop_cd'    , //店舗コード
				''       , //店舗名
				''      , //
			);
	
			$csvheads    = array();
			$col_index   = array();
			
			foreach ($col_heads as $k => $v) {
				if (!empty($v)) {
					$csvheads[$k]  = $v;
					$col_index[$v] = $k;
				}
			} 
			
			$key1 = $col_index['shop_cd'];//キーです、必ず仕様します
			$key2 = $col_index['dm_no'];//キーです、必ず仕様します
			
			$err   = new Class_ERROR("","") ;
			$dao   = new Class_M_COST_DM_COUNT ;
			$daodm = new Class_M_COST_DM ;
			
			$ngline      = 0;
			$error_times = 0;
			$error_stop  = IMPORT_STOP_MAX_ERROR_TIMES;
			$errtext     = array();
			$isng        = FALSE;
			$chk         = $dao->get_checks();
			
			$where[] = " matrix_cd ='{$martrix_cd}' " ;
			$page = NULL;
			if ( $dmdatas = $daodm->search( $where,$page,$martrix_cd ) ) {
				foreach($dmdatas as $k =>$v ) {
					$dm_no_datas[$v["dm_no"]] = $v["id"] ;
				}
			}
			
			$dm_no_cols = array();
			$max_cols = count($rethead);
			
			for ($i=2;$i<$max_cols; $i++) {
				$dm_no_cols[$i] = str_replace("NO","", $rethead[$i]); 
				if (empty($dm_no_datas[ $dm_no_cols[$i] ] )){
					$ngMsg_tmp[0][] = "差替ＮＯ:{$dm_no_cols[$i]} は存在しません。<br>";
					$error_times++;
				}
			}
			
			
			$shops     =  Class_M_OTHER::get_shop_array(NULL);

			if ( $error_times > 0 ) {
				++$ngline;
			} 

			$linecount = count($rowall);
			$percentold = 100;
 			foreach ($rowall as $line => $row) {
				$isng = FALSE;
				$percent = intval($line/$linecount * 100)."%";
				if  ( $percent != $percentold ) {
					Class_FILE_CSV::write_msg_checking_per( $percent ) ;
				}
				$percentold = $percent;
				//CSV内部重複不可チェック
				foreach ($rowall as $kk=>$vv) {
					if  ($line != $kk) {
						if ( ($row[$key1] == $vv[$key1]) && ($row[$key2] == $vv[$key2]) ){
							$col1 = $key1 + 1;
							$col2 = $key2 + 1;
							$isng = TRUE;
							$ngMsg_tmp[$line][] = "{$line}行と{$kk}行の({$col1}+{$col2})列目の値重複不可。";
							$error_times++;
							if ($error_times > $error_stop) {
								break;
							}
						}
					}
				} 
				
				//一般チェック
				
					foreach ( $csvheads as $k=>$v ) {
						$msg =  $err->check( $rowall[$line][$k], $chk[$v ] ); 
						if (!empty($msg)) {
							$isng = TRUE;
							$col  = $k+1;
							$ngMsg_tmp[$line][] = "{$line}行{$col}列目：{$msg}。";
							$error_times++;					
							if ($error_times > $error_stop) {
								break;
							}
						}
					}
					
					for ($j=2;$j<$max_cols; $j++) {
						if ( !empty($row[$j]) ) {
							//echo "-{$j}-".$row[$j] ."**";
							 $rowall[$line][$j] = str_replace(",","", $row[$j] ); 
							$msg = $err->check( $rowall[$line][$j], array("NUM") );
							if (!empty($msg)) {
								$isng = TRUE;
								$col  = $j+1;
								$ngMsg_tmp[$line][] = "{$line}行{$col}列目：{$msg}。<br>";
								$error_times++;					
								if ($error_times > $error_stop) {
									break;
								}
							}
						}
					}
					
					//店舗チェック
					if (empty($shops[$row[$key1]])) {
						$col1 = $key1 + 1;
						$isng = TRUE;
						$error_times++;
						$ngMsg_tmp[$line][]   = "{$line}行{$col1}列目：{$row[$key1]}店舗スマスタに存在しません。";
					}
				if ( $isng ) {
					++$ngline;
					$errtext[$ngline] = $row;
					if ($error_times > $error_stop) {
						break;
					}
				}
			}
			
			if ($ngline > 0) {
				$errHtml = Class_FILE_CSV::format_msg($ngMsg_tmp);
				if ($error_times > $error_stop) {
					Class_FILE_CSV::write_msg_error( $errHtml ,$error_stop );	
				
				} else {
					Class_FILE_CSV::write_msg_error( $errHtml );	
				}
			} else {
				//DBへ更新
				
				try {
					$daodb = $dao->get_db();
					$dao->begin_trans();
					$i = 0;
					$percent = "";
					$percentold = "";
					
					foreach ( $rowall as $k=>$v ) {
						$i++;
						$percent = intval($i/$line * 100)."%";
						if  ( $percent != $percentold ) {
							Class_FILE_CSV::write_msg_doing( $percent ) ;
						}
						$percentold = $percent;
						$values  = array();
						
						foreach ( $csvheads as $kk => $vv ) {
							$values[$vv] = $v[$kk];
						}
						
						$values["matrix_cd"] = $martrix_cd;
						$keyvalues =  $values[$col_heads[$key1]];
						for ($j=2;$j<$max_cols; $j++) {
							if ( !empty($v[$j]) ) {
								$values["dm_no"] = $dm_no_cols[$j];
								$values["count"] = $v[$j];
								$where = sprintf(" {$col_heads[$key1]} = '%s' and matrix_cd = '{$martrix_cd}' and dm_no = '{$dm_no_cols[$j]}'  "  , $dao->quote($keyvalues) );
								if ( $dao->exits( $where ) ) {
									if (!($dao->editbywhere( $where, $values ))) {
										throw  new Exception("mcost_dm_c_import db更新");
									}
								} else {
									if ( !( $dao->add($values ) ) ) {
										throw  new Exception("mcost_dm_c_import登録");
									}
								}
							}
						}
					}
					//Class_FILE_CSV::write_msg_succed($line, "mcost_dm_c");
					$dao->commit_trans();
					
				} catch (Exception $e) {
					$dao->rollback_trans();
					Class_FILE_CSV::write_msg_error( "DB Exceptionがありました。</br>" );
				}
				
			} 
		}else {

		$errHtml = "CSVファイルエラー";
		Class_FILE_CSV::write_msg_error( $errHtml );
			
		}
		
		// ロケール情報の復元
		setlocale(LC_ALL, $locale);
	
	}else {

		$errHtml = "CSVファイルエラー";
		Class_FILE_CSV::write_msg_error( $errHtml );
	}
?>
</body>
	</himl>
	